// 路由: 博客接口

const {
  getBlogList,
  getDetailById,
  newBlog,
  updateBlog,
  deleteBlog
} = require('../controller/blog');
const { SuccessModel, ErrorModel } = require('../model/resModel');

const handleBlogRouter = (req, res) => {
  const method = req.method;
  const path = req.path;
  const id = req.query.id;

  // 获取博客列表
  if (method === 'GET' && path === '/api/blog/list') {
    const keyword = req.query.keyword || '';
    const author = req.query.author || '';
    const result = getBlogList(keyword, author);
    return result.then(listData => {
      return new SuccessModel(listData);
    })
  }

  // 获取博客详情
  if (method === 'GET' && path === '/api/blog/detail') {
    const result = getDetailById(id);
    return result.then(detailData => {
      return new SuccessModel(detailData)
    })
  }

  // 新建博客
  if (method === 'POST' && path === '/api/blog/new') {
    const result = newBlog(req.body);
    return result.then(data => {
      return new SuccessModel(data)
    })
  }
  // 更新博客
  if (method === 'POST' && path === '/api/blog/update') {
    const result = updateBlog(id, req.body);
    return result.then(data => {
      if (data) {
        return new SuccessModel(data)
      } else {
        return new ErrorModel('更新博客失败')
      }
    })
  }
  // 删除博客
  if (method === 'POST' && path === '/api/blog/delete') {
    const author = 'xiaoming';
    const result = deleteBlog(id, author);
    return result.then(data => {
      if (data) {
        return new SuccessModel(data)
      } else {
        return new ErrorModel('删除数据失败')
      }
    })
  }
}


module.exports = handleBlogRouter
